<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 用户管理
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.userName" placeholder="用户名" class="filter-item handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">搜索</el-button>
                <el-button type="primary" icon="el-icon-plus" class="filter-item" @click="handleAdd">新增</el-button>
            </div>
            <el-table
                :data="tableData"
                v-loading="loading"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="loginName" label="登录名"></el-table-column>
                <el-table-column prop="userName" label="用户名"></el-table-column>
                <el-table-column label="头像" align="center">
                    <template slot-scope="scope">
                        <el-image
                            class="table-td-thumb"
                            :src="scope.row.headLogo"
                            :preview-src-list="[scope.row.headLogo]"
                        ></el-image>
                    </template>
                </el-table-column>

                <el-table-column prop="createTime" label="创建时间">
                    <template slot-scope="scope">
                        <span>{{ parseDateTime(scope.row.createTime) }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            icon="el-icon-edit"
                            @click="handleEdit(scope.$index, scope.row)"
                        >编辑</el-button>
                        <!--<el-button
                            type="text"
                            icon="el-icon-delete"
                            class="red"
                            @click="handleDelete(scope.$index, scope.row)"
                        >删除</el-button>-->
                    </template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination
                    background
                    layout="total, prev, pager, next"
                    :current-page="query.current"
                    :page-size="query.size"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" :rules="rules" label-width="70px">
                <el-form-item label="登陆名" prop="loginName" required >
                    <el-input v-model="form.loginName"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="userName">
                    <el-input v-model="form.userName"></el-input>
                </el-form-item>
                <el-form-item label="头像">
                    <el-upload
                            ref="upload"
                            class="avatar-uploader"
                            action=""
                            :http-request="fileUpload"
                            :show-file-list="false"
                            :before-upload="beforeAvatarUpload">
                        <img v-if="form.headLogo" :src="form.headLogo" class="avatar">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="角色">
                    <template>
                        <el-checkbox :indeterminate="form.isIndeterminate" v-model="form.checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                        <div style="margin: 15px 0;"></div>
                        <el-checkbox-group v-model="form.checkedCities" @change="handleCheckedCitiesChange">
                            <el-checkbox v-for="city in form.cities" :label="city.id" :key="city.id">{{city.roleName}}</el-checkbox>
                        </el-checkbox-group>
                    </template>
                </el-form-item>

                <el-form-item label="部门">
                    <el-tree
                            :data="form.sysDeptAll"
                            show-checkbox
                            check-strictly
                            node-key="id"
                            ref="tree"
                            :default-checked-keys="form.checkedKeys"
                            :props="defaultPropsDept">
                    </el-tree>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" :disabled="formLoading" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { sysUserPage,sysUserCheckUnique,saveSysUser,updateSysUser,delSysUser } from '../../api/sysUser';
import { sysUserRoleList } from '../../api/sysUser';
import { sysDeptPage,sysDeptAndCheckedList } from '../../api/sysDept';
import { fileUpload } from '../../api/uploadFile';

import SelectTree from '../../components/common/SelectTree.vue';

export default {
    name: 'sys-user-list',
    data() {
        let checkUnique = (rule, value, callback) => {
            /*if (!value) {
                return callback(new Error('登录名不能为空'));
            }*/
            let userId = this.form.id;
            sysUserCheckUnique({userId:userId,loginName:value}).then(res => {
                if (res.code != 0) {
                    callback(new Error(res.msg));
                } else {
                    callback();
                }
            });
        };
        return {
            // 遮罩层
            loading: true,
            formLoading: false,
            query: {
                userName: '',
                current: 1,
                size: 10
            },
            tableData: [],
            editVisible: false,
            pageTotal: 0,
            defaultProps: {
                children: 'children',
                label: 'name'
            },
            defaultPropsDept: {
                children: 'children',
                label: 'name'
            },
            form: {
                loginName:'',
                userName:'',
                headLogo:'',
                sysDeptAll:[],
                checkedKeys:[],
                checkAll: false,
                checkedCities: [],
                cityIds: [],
                cities: [],
                isIndeterminate: false
            },
            idx: -1,
            id: -1,
            rules: {
                loginName: [
                    { validator:checkUnique, trigger: 'blur' }
                ]
            }
        };
    },
    components: {
        SelectTree
    },
    created() {
        this.defaultform = JSON.parse(JSON.stringify(this.form));
        this.getData();
    },
    destroyed() {
        this.defaultform = null;
    },
    methods: {
        // 获取 easy-mock 的模拟数据
        getData() {
            this.loading = true;
            sysUserPage(this.query).then(res => {
                this.loading = false;
                this.tableData = res.data;
                this.pageTotal = res.count;
            });
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'current', 1);
            this.getData();
        },
        // 删除操作
        handleDelete(index, row) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    delSysUser(row.id).then(res => {
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`删除成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                })
                .catch(() => {});
        },
        handleAdd(){
            this.form = Object.assign({}, this.defaultform);
            sysDeptAndCheckedList({}).then(res => {
                this.form.sysDeptAll = res.sysDeptList;
                this.form.checkedKeys = res.checkedDeptIds;
            });
            sysUserRoleList({}).then(res => {
                this.form.cities = res.sysRoleList;
                this.form.cityIds = res.sysRoleIdList;
            });
            this.editVisible = true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            })
        },
        // 编辑操作
        handleEdit(index, row) {
            this.idx = index;
            this.form.id = row.id;
            this.form.loginName = row.loginName;
            this.form.userName = row.userName;
            this.form.headLogo = row.headLogo;
            // :default-expanded-keys="[2, 3]"，默认打开
            // 整个menu，及当前用户所拥有的的权限
            sysDeptAndCheckedList({userId:row.id}).then(res => {
                this.form.sysDeptAll = res.sysDeptList;
                this.form.checkedKeys = res.checkedDeptIds;
            });
            sysUserRoleList({userId:row.id}).then(res => {
                this.form.cities = res.sysRoleList;
                this.form.checkedCities = res.userRoleList;
                this.form.cityIds = res.sysRoleIdList;
                // 判断全选
                if (this.form.checkedCities != null && this.form.checkedCities.length > 0 &&
                    this.form.cityIds != null && this.form.cityIds.length > 0 &&
                    this.form.checkedCities.length === this.form.cityIds.length) {
                    this.form.checkAll = true;
                    this.form.isIndeterminate = false;
                } else if (this.form.checkedCities != null && this.form.checkedCities.length > 0) {
                    this.form.isIndeterminate = true;
                    this.form.checkAll = false;
                }
            });
            this.editVisible = true;
            this.$nextTick(()=>{
                this.$refs['form'].clearValidate();
            })
        },
        // 保存编辑
        saveEdit() {
            this.$refs['form'].validate((valid) => {
                if (!valid) {
                    console.log('error submit!!');
                    return false;
                }
                this.formLoading = true;
                // 角色选择，checkedCities
                let checked = this.form.checkedCities;
                if (checked == null || checked <= 0) {
                    this.$message.error(`请选择角色`);
                    this.formLoading = false;
                    return false;
                }
                this.form.roleIds = checked.join(",");
                // 部门选择
                // tree的值获取
                let nodes = this.$refs.tree.getCheckedNodes();
                if (nodes == null || nodes <= 0) {
                    this.$message.error(`请选择部门`);
                    this.formLoading = false;
                    return false;
                }
                let deptIdArr = [];
                nodes.forEach(item => {
                    deptIdArr.push(item.id);
                })
                this.form.deptIds = deptIdArr.join(",");
                if (this.form.id) {
                    updateSysUser(this.form).then(res => {
                        this.formLoading = false;
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`修改成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                } else {
                    saveSysUser(this.form).then(res => {
                        this.formLoading = false;
                        if (res.code == 0) {
                            this.editVisible = false;
                            this.$message.success(`保存成功`);
                            this.getData();
                        } else {
                            this.$message.error(res.msg);
                            return false;
                        }
                    });
                }
            });
        },
        beforeAvatarUpload(file) {
            const isJPG = file.type === 'image/jpeg';
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isJPG) {
                this.$message.error('上传头像图片只能是 JPG 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }
            return isJPG && isLt2M;
        },
        fileUpload(file){
            let _this = this;
            return fileUpload(file).then(res => {
                // 多图片上传，结果data里面是一个array
                // console.log(res.data[0]);
                _this.form.headLogo = res.data[0]
                // _this.handleAvatarSuccess(res, file)
                _this.$refs.upload.clearFiles();//清空
            });
        },
        handleCheckAllChange(val) {
            this.form.checkedCities = val ? this.form.cityIds : [];
            this.form.isIndeterminate = false;
        },
        handleCheckedCitiesChange(value) {
            let checkedCount = value.length;
            this.form.checkAll = checkedCount === this.form.cities.length;
            this.form.isIndeterminate = checkedCount > 0 && checkedCount < this.form.cities.length;
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'current', val);
            this.getData();
        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
.avatar-uploader  {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    width: 148px;
    height: 148px;
    position: relative;
    overflow: hidden;
}
.avatar-uploader:hover {
    border-color: #409EFF;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
}
.avatar {
    width: 148px;
    height: 148px;
    display: block;
}
</style>
